<template>
    <div class="add-friend-container">
        <div class="request-list">
            <h3>好友请求</h3>
            <!-- 无请求时显示提示 -->
            <div v-if="friendRequests.length === 0" class="no-requests">
                暂无好友请求
            </div>
            <div v-for="req in friendRequests" :key="req.friendRequestId" class="request-item">
                <img :src="req.avatarUrl || '/images/avatar-default.png'" alt="头像" class="avatar">
                <div class="request-info">
                    <div class="req-username">{{ req.userName }}</div>
                    <div class="req-reason">{{ req.reason || '无附加信息' }}</div>
                    <!-- 状态显示 -->
                    <div class="req-status" v-if="req.status !== 'pending'"
                        :class="{ 'accepted': req.status === 'accepted', 'rejected': req.status === 'rejected' }">
                        {{ req.status === 'accepted' ? '已接受' : '已拒绝' }}
                    </div>
                </div>
                <div class="request-actions" v-if="req.status === 'pending'">
                    <button @click="handleRequest(req, true)">接受</button>
                    <button @click="handleRequest(req, false)">拒绝</button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, defineEmits, watch } from 'vue';
import request from '../utils/request';

const emit = defineEmits(['close', 'refresh-friends', 'request-processed']);
const friendRequests = ref([]);
// 本地缓存已处理的请求
const processedRequestsCache = ref([]);

// 加载好友请求列表
const loadFriendRequests = async () => {
    try {
        const userId = localStorage.getItem('userId');
        const res = await request.get('/user/getRequestMessage', {
            params: { userId }
        });
        if (res.data.code === 'SUCCESS') {
            let backendRequests = res.data.data || [];
            // 合并后端数据和本地缓存
            const mergedRequests = [...backendRequests];
            processedRequestsCache.value.forEach(cached => {
                const index = mergedRequests.findIndex(r => r.friendRequestId === cached.friendRequestId);
                if (index > -1) {
                    mergedRequests[index] = cached;
                } else {
                    mergedRequests.push(cached);
                }
            });
            // 排序
            friendRequests.value = mergedRequests.sort((a, b) => {
                if (a.status === 'pending' && b.status !== 'pending') return -1;
                if (a.status !== 'pending' && b.status === 'pending') return 1;
                const timeA = new Date(a.createTime || a.processedAt || 0).getTime();
                const timeB = new Date(b.createTime || b.processedAt || 0).getTime();
                return timeB - timeA;
            });
        }
    } catch (error) {
        console.error('加载好友请求失败', error);
    }
};

// 处理好友请求（接受/拒绝）
const handleRequest = async (req, accept) => {
    try {
        const res = await request.get('/user/handleRequest', {
            params: {
                friendRequestId: req.friendRequestId,
                resp: accept
            }
        });

        if (res.data.code === 'SUCCESS') {
            // 记录处理状态到本地缓存
            const processedStatus = accept ? 'accepted' : 'rejected';
            const updatedReq = {
                ...req,
                status: processedStatus,
                processedAt: new Date().toISOString()
            };

            // 更新缓存
            const cacheIndex = processedRequestsCache.value.findIndex(
                r => r.friendRequestId === req.friendRequestId
            );
            if (cacheIndex > -1) {
                processedRequestsCache.value[cacheIndex] = updatedReq;
            } else {
                processedRequestsCache.value.push(updatedReq);
            }

            // 刷新列表
            await loadFriendRequests();
            emit('refresh-friends');
            emit('request-processed');
        }
    } catch (error) {
        console.error('处理好友请求失败', error);
        alert('处理失败：' + (error.message || '网络异常'));
    }
};

// 组件挂载时初始化
onMounted(() => {
    // 从localStorage恢复缓存
    const savedCache = localStorage.getItem('processedFriendRequests');
    if (savedCache) {
        try {
            processedRequestsCache.value = JSON.parse(savedCache);
        } catch (e) {
            console.error('恢复缓存失败', e);
            localStorage.removeItem('processedFriendRequests');
        }
    }

    // 加载请求列表
    loadFriendRequests();

    // WebSocket监听新请求
    if (window.ws) {
        window.ws.addEventListener('message', (event) => {
            const data = JSON.parse(event.data);
            if (data.type === 'friend_request') {
                loadFriendRequests();
            }
        });
    }
});

// 监听缓存变化，持久化到localStorage
watch(processedRequestsCache, (newVal) => {
    localStorage.setItem('processedFriendRequests', JSON.stringify(newVal));
}, { deep: true });

// 暴露方法给父组件
defineExpose({
    loadFriendRequests
});
</script>

<style scoped>
.add-friend-container {
    width: 320px;
    background-color: rgba(255, 255, 255, 0.6);
    border-right: 1px solid #e1d7d7;
    display: flex;
    flex-direction: column;
    height: 100vh;
    position: relative;
}

.add-friend-container h3 {
  text-align: center; /* 水平居中 */
  margin: 0; /* 清除默认margin */
  padding: 15px 0; /* 上下内边距，可根据需要调整 */
}

.request-list {
    margin-top: 30px;
}

.request-list h3 {
    margin-bottom: 15px;
    font-size: 16px;
    color: #333;
}

.no-requests {
    text-align: center;
    padding: 20px;
    color: #999;
    font-size: 14px;
}

.request-item {
    display: flex;
    align-items: center;
    padding: 10px;
    border-bottom: 1px solid #eee;
}

.request-item:hover {
    background-color: #f9f9f9;
}

.avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    object-fit: cover;
}

.request-info {
    flex: 1;
    margin: 0 15px;
}

.req-username {
    font-weight: 500;
    margin-bottom: 4px;
}

.req-reason {
    font-size: 12px;
    color: #666;
}

.request-actions button {
    padding: 4px 10px;
    margin-left: 8px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: opacity 0.2s;
}

.request-actions button:hover {
    opacity: 0.9;
}

.request-actions button:first-child {
    background-color: #07c160;
    color: white;
}

.request-actions button:last-child {
    background-color: #f5f5f5;
    color: #333;
}

.req-status {
    font-size: 12px;
    padding: 2px 6px;
    border-radius: 4px;
    display: inline-block;
    margin-top: 4px;
}

.req-status.accepted {
    color: #07c160;
    background-color: rgba(7, 193, 96, 0.1);
}

.req-status.rejected {
    color: #ff4d4f;
    background-color: rgba(255, 77, 79, 0.1);
}
</style>